﻿using moc.Models;
using moc.IDAL;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;

namespace moc.DAL
{
    public class BaseDal<T> where T:class,new()
    {
        private MocDbContext _db = null;
        public BaseDal() { }
        public BaseDal(MocDbContext db)
        {
            _db = db;
        }
        public virtual T Add(T entity)
        {
            _db.Set<T>().Add(entity);
            return entity;
        }
        public virtual void Delete(List<T> list) 
        {
            _db.Set<T>().RemoveRange(list);
        }
        public virtual T Update(T entity)
        {
            _db.Set<T>().Update(entity);
            return entity;
        }
        public virtual IQueryable<T> LoadEntities(Expression<Func<T,bool>> whereLambda)
        {            
            return _db.Set<T>().Where(whereLambda);
        }
        public IQueryable<T> LoadPage<S>(int pageSize,int pageIndex,out int total,Expression<Func<T,bool>> whereLambda,Expression<Func<T,S>> orderByLambda,bool isAsc )
        {
            total = _db.Set<T>().Where(whereLambda).Count();
            if (isAsc)
            {
                return _db.Set<T>().Where(whereLambda)
                .OrderBy(orderByLambda)
                .Skip(pageIndex)
                .Skip(pageSize);
            }
            return _db.Set<T>().Where(whereLambda)
                .OrderByDescending(orderByLambda)
                .Skip(pageIndex)
                .Skip(pageSize);
        }      
    }
}
